<template>
  <div>
    <!-- 返回 -->
    <top-back>
      <template v-slot:back>新增收货地址</template>
    </top-back>

    <!-- 编辑 -->
    <form @submit.prevent>
      <div class="addresscard">
        <van-field
          v-model="singleAddress.name"
          label="收件人"
          placeholder="请输入收件人姓名"
        />
        <van-field
          v-model="singleAddress.tel"
          label="电话"
          placeholder="请输入收件人电话"
        />
        <van-field
          v-model="address"
          label="地区"
          placeholder="请输入选择 省 / 市 / 区"
          @click="isShow = !isShow"
        />
        <van-action-sheet v-model="isShow">
          <van-area
            :area-list="areaList"
            @confirm="onChoseAddress"
            @cancel="isShow = false"
          />
        </van-action-sheet>
        <van-field
          v-model="detail"
          label="详细地址"
          placeholder="街道门牌、楼层房间号等信息"
        />
      </div>

      <div class="addresscard">
        <van-cell title="设为默认收货地址">
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <van-switch
              v-model="checked"
              size="24"
              @click="singleAddress.isDefault = !singleAddress.isDefault"
            />
          </template>
        </van-cell>
      </div>

      <van-button block class="update" @click="update">保存</van-button>
    </form>
  </div>
</template>

<script>
import TopBack from '@/components/Mine/TopBack'
import { Toast } from 'vant'
import { areaList } from '@vant/area-data'

export default {
  name: 'AddAddress',
  components: {
    TopBack
  },
  data () {
    return {
      searchResult: [],
      areaList,
      isShow: false,
      checked: false,
      address: '',
      detail: '',
      singleAddress: {
        id: Math.floor(Math.random() * 10000 - 1),
        name: '',
        tel: '',
        address: '',
        isDefault: this.checked
      },
      newAddress: {}
    }
  },
  methods: {
    update () {
      this.singleAddress.address = this.address + ' ' + this.detail
      for (const k in this.singleAddress) {
        this.newAddress[k] = this.singleAddress[k]
      }
      this.$store.dispatch('addAddress', this.newAddress)
      Toast('添加成功')
      this.$router.go(-1)
    },
    onChoseAddress (val) {
      this.address = val.map(item => item.name).join('')
      this.isShow = false
    }
  }
}
</script>

<style lang="scss" scoped>
.addresscard {
  width: 7.1rem;
  margin: 0.2rem auto;
  padding: 0.1rem;
  border-radius: 24px;
  overflow: hidden;
}
.update {
  width: 7.1rem;
  margin: 30px auto;
  border-radius: 22px;
}
</style>
